import React, { useEffect, useState } from 'react';
import axios from '../../../axios';
import { NavBar, Card, Image, Space, Tag, List, Avatar, Button, Input, Toast, Tabs, Dialog } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import {
  LikeOutline,
  MessageOutline,
  LocationFill,
  UserOutline,
  EnvironmentOutline
} from 'antd-mobile-icons';
import './SocialFeed.css';

type TabKey = 'follow' | 'recommend' | 'city';

interface TabItem {
  key: TabKey;
  title: string;
}

interface User {
  _id: string;
  userName: string;
  img: string
}

interface Comment {
  text: string;
  timestamp: string;
  user_id: User;
}

interface Post {
  _id: string;
  id?: string;
  user_id: User;
  content?: string;
  title?: string;
  img?: string;
  media_type?: 'image' | 'video';
  location?: string;
  address?: string;
  time?: string;
  createdAt?: string;
  like: string[];
  comment: Comment[];
}

interface RawPost extends Omit<Post, 'user_id'> {
  user_id: string;
  userName?: string;
  userImg?: string;
}

interface VideoPlayerState {
  [key: string]: {
    hasPreviewed: boolean;
    isPreviewEnded: boolean;
  }
}

const tabItems: TabItem[] = [
  { key: 'follow', title: '关注' },
  { key: 'recommend', title: '推荐' },
  { key: 'city', title: '同城' }
];

function formatDateTime(dateString: string | undefined): string {
  if (!dateString) return '';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return '';
  const pad = (n: number): string => n.toString().padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}`;
}

const SocialFeedPage = () => {
  const navigate = useNavigate();
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<TabKey>('recommend');
  const [commentInputs, setCommentInputs] = useState<Record<string, string>>({});
  const [followedUsers, setFollowedUsers] = useState<string[]>([]);
  const [allPosts, setAllPosts] = useState<Post[]>([]);
  const currentUserId = localStorage.getItem('user_id');
  const [videoStates, setVideoStates] = useState<VideoPlayerState>({});

  const fetchFollowedUsers = async () => {
    if (!currentUserId) return;
    try {
      const response = await axios.get(`/llx/following/${currentUserId}`);
      if (response.data.code === 200) {
        setFollowedUsers(response.data.following || []);
      }
    } catch (err) {
      console.error('获取关注列表失败:', err);
    }
  };

  const fetchPosts = async () => {
    setLoading(true);
    try {
      const res = await axios.get('/llx/list');
      let data: Post[] = res.data?.data || [];
      if (!Array.isArray(data)) data = [];
      
      data = data.map(post => {
        // 确保基本字段存在
        const processedPost = {
          ...post,
          like: Array.isArray(post.like) ? post.like : [],
          comment: Array.isArray(post.comment) ? post.comment : [],
          img: post.img || '',
          media_type: post.media_type || 'image'
        };

        // 处理视频URL
        if (processedPost.media_type === 'video' && processedPost.img) {
          // 确保视频URL是字符串
          if (typeof processedPost.img === 'object') {
            const videoData = processedPost.img as any;
            processedPost.img = videoData.src || videoData.url || '';
          }
          
          // 添加协议如果缺少
          if (processedPost.img && !processedPost.img.startsWith('http')) {
            processedPost.img = `http://localhost:3000${processedPost.img}`;
          }
        }

        console.log('处理后的帖子数据:', processedPost);
        return processedPost;
      });
      
      setAllPosts(data);
      
      if (activeTab === 'follow') {
        const filteredPosts = data.filter(post => 
          followedUsers.includes(post.user_id?._id)
        );
        setPosts(filteredPosts);
      } else {
        setPosts(data);
      }
    } catch (err) {
      console.error('获取动态失败:', err);
      Toast.show({ icon: 'fail', content: '获取动态失败' });
      setPosts([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFollowedUsers();
  }, [currentUserId]);

  useEffect(() => {
    fetchPosts();
  }, [activeTab, followedUsers]);

  const handleLike = async (postId: string) => {
    if (!currentUserId) {
      Toast.show({ icon: 'fail', content: '请先登录' });
      return;
    }
    try {
      const response = await axios.post('/llx/like', {
        postId,
        user_id: currentUserId
      });
      if (response.data.code === 200) {
        setPosts(prevPosts =>
          prevPosts.map(post => {
            if (post._id === postId) {
              return {
                ...post,
                like: response.data.like
              };
            }
            return post;
          })
        );
        Toast.show({ icon: 'success', content: response.data.message });
      }
    } catch (err) {
      console.error('点赞失败:', err);
      Toast.show({ icon: 'fail', content: '操作失败，请稍后重试' });
    }
  };

  const handleComment = async (postId: string) => {
    if (!currentUserId) {
      Toast.show({ icon: 'fail', content: '请先登录' });
      return;
    }
    const commentText = commentInputs[postId];
    if (!commentText?.trim()) {
      Toast.show({ icon: 'fail', content: '请输入评论内容' });
      return;
    }
    try {
      const response = await axios.post('/llx/comment', {
        postId,
        text: commentText.trim(),
        userId: currentUserId
      });
      if (response.data.code === 200) {
        setCommentInputs(prev => ({ ...prev, [postId]: '' }));
        setPosts(prevPosts =>
          prevPosts.map(post => {
            if (post._id === postId) {
              return {
                ...post,
                comment: [...post.comment, response.data.comment]
              };
            }
            return post;
          })
        );
        Toast.show({ icon: 'success', content: '评论成功' });
      }
    } catch (err) {
      console.error('评论失败:', err);
      Toast.show({ icon: 'fail', content: '评论失败，请稍后重试' });
    }
  };

  const handleCommentInputChange = (postId: string, value: string) => {
    setCommentInputs(prev => ({
      ...prev,
      [postId]: value
    }));
  };

  const handleFollow = async (userId: string) => {
    if (!currentUserId) {
      Toast.show({ icon: 'fail', content: '请先登录' });
      return;
    }
    if (userId === currentUserId) {
      Toast.show({ icon: 'fail', content: '不能关注自己' });
      return;
    }
    try {
      const response = await axios.post('/llx/follow', {
        followerId: currentUserId,
        followingId: userId
      });
      if (response.data.code === 200) {
        Toast.show({ icon: 'success', content: response.data.message });
        if (response.data.message.includes('成功关注')) {
          setFollowedUsers(prev => [...prev, userId]);
        } else {
          setFollowedUsers(prev => prev.filter(id => id !== userId));
        }
        if (activeTab === 'follow') {
          fetchPosts();
        }
      }
    } catch (err) {
      console.error('关注失败:', err);
      Toast.show({ icon: 'fail', content: '关注失败，请稍后重试' });
    }
  };

  const handleAvatarClick = (userId: string) => {
    navigate(`/detail?userId=${userId}`);
  };

  const handleVideoPreview = (postId: string, video: HTMLVideoElement) => {
    // 设置预览时间
    const previewTime = 10;
    
    // 移除加载中文字
    const loadingText = video.parentElement?.querySelector('.loading-text');
    if (loadingText) {
      loadingText.remove();
    }

    // 直接尝试播放视频
    video.play().catch(error => {
      console.error('播放失败:', error);
      // 如果自动播放失败，静默处理，让用户可以通过视频控件手动播放
    });

    // 监听时间更新
    const timeUpdateHandler = () => {
      if (video.currentTime >= previewTime) {
        // 停止播放
        video.pause();
        video.removeEventListener('timeupdate', timeUpdateHandler);

        // 标记预览结束
        setVideoStates(prev => ({
          ...prev,
          [postId]: {
            hasPreviewed: true,
            isPreviewEnded: true
          }
        }));

        // 显示下载提示
        Toast.show({
          content: '预览结束，请下载视频观看完整内容',
          duration: 1500,
          afterClose: () => {
            Dialog.confirm({
              content: '是否要重新预览视频？',
              onConfirm: () => {
                // 重置视频状态
                video.currentTime = 0;
                setVideoStates(prev => ({
                  ...prev,
                  [postId]: {
                    hasPreviewed: false,
                    isPreviewEnded: false
                  }
                }));
                // 重新开始预览
                handleVideoPreview(postId, video);
              }
            });
          }
        });
      }
    };

    video.addEventListener('timeupdate', timeUpdateHandler);
  };

  return (
    <div className="social-feed-page">
      <NavBar backArrow={false}>社交动态</NavBar>
      <Tabs
        activeKey={activeTab}
        onChange={(key: string) => setActiveTab(key as TabKey)}
        style={{ background: '#fff' }}
      >
        {tabItems.map(tab => (
          <Tabs.Tab title={tab.title} key={tab.key}>
            {tab.title}
          </Tabs.Tab>
        ))}
      </Tabs>
      <div className="feed-content">
        {loading ? (
          <div style={{ textAlign: 'center', marginTop: 40 }}>加载中...</div>
        ) : posts.length === 0 ? (
          <div style={{ textAlign: 'center', marginTop: 40 }}>暂无动态</div>
        ) : (
          posts.map(post => (
            <div key={post._id || post.id}>
              <Card className="post-card">
                <div className="post-header">
                  <Avatar 
                    src={post.user_id?.img} 
                    className="user-avatar" 
                    onClick={() => handleAvatarClick(post.user_id?._id)}
                    style={{ cursor: 'pointer' }}
                  />
                  <div className="user-info">
                    <div className="user-name">{post.user_id?.userName || '匿名'}</div>
                  </div>
                  {post.user_id?._id !== currentUserId && (
                    <Button 
                      size="small" 
                      style={{ marginLeft: 'auto' }}
                      onClick={() => handleFollow(post.user_id?._id)}
                      color={followedUsers.includes(post.user_id?._id) ? 'primary' : 'default'}
                    >
                      {followedUsers.includes(post.user_id?._id) ? '已关注' : '关注'}
                    </Button>
                  )}
                </div>
                <div className="post-timestamp" style={{ marginLeft: 0, marginTop: 2, color: '#888', fontSize: 12, lineHeight: 1 }}>
                  {formatDateTime(post.time || post.createdAt)}
                </div>
                <div className="post-body">
                  <p className="post-text">{post.content || post.title || ''}</p>
                  {post.img && post.media_type === 'image' && (
                    <div className="image-container">
                      <img 
                        src={post.img.startsWith('http') ? post.img : `http://localhost:3000${post.img}`} 
                        className="post-media" 
                        alt="图片"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          console.error('图片加载失败:', {
                            src: target.src,
                            originalSrc: post.img,
                            postId: post._id
                          });
                          target.style.display = 'none';
                          // 显示错误提示
                          const container = target.parentElement;
                          if (container) {
                            const errorDiv = document.createElement('div');
                            errorDiv.className = 'media-error';
                            errorDiv.textContent = '图片加载失败';
                            container.appendChild(errorDiv);
                          }
                        }}
                      />
                    </div>
                  )}
                  {post.img && post.media_type === 'video' && (
                    <div className="video-container">
                      <video
                        key={post._id}
                        className="post-media"
                        controls
                        preload="metadata"
                        playsInline
                        controlsList="nodownload"
                        onLoadStart={(e) => {
                          const video = e.currentTarget;
                          // 确保没有加载文字
                          const container = video.parentElement;
                          if (container) {
                            const loadingText = container.querySelector('.loading-text');
                            if (loadingText) {
                              loadingText.remove();
                            }
                          }
                        }}
                        onLoadedMetadata={(e) => {
                          const video = e.currentTarget;
                          // 再次确保没有加载文字
                          const container = video.parentElement;
                          if (container) {
                            const loadingText = container.querySelector('.loading-text');
                            if (loadingText) {
                              loadingText.remove();
                            }
                          }

                          // 检查是否已经预览过
                          if (!videoStates[post._id]?.hasPreviewed) {
                            handleVideoPreview(post._id, video);
                          }
                        }}
                        onError={(e) => {
                          const video = e.currentTarget;
                          video.style.display = 'none';
                          const container = video.parentElement;
                          if (container) {
                            const errorDiv = document.createElement('div');
                            errorDiv.className = 'media-error';
                            errorDiv.textContent = '视频加载失败';
                            container.appendChild(errorDiv);
                          }
                        }}
                        src={post.img}
                      >
                        <track kind="captions" />
                      </video>
                    </div>
                  )}
                  {post.location && (
                    <div className="post-location">
                      <LocationFill fontSize={16} />
                      <span style={{ marginLeft: '4px' }}>{post.location}</span>
                    </div>
                  )}
                </div>
                <div className="post-actions">
                  <Space>
                    <Button
                      size="small"
                      color={post.like.includes(currentUserId || '') ? 'danger' : 'default'}
                      onClick={() => handleLike(post._id)}
                      fill="none"
                      className="action-button"
                    >
                      <LikeOutline />
                      <span style={{ marginLeft: '4px' }}>{post.like.length}</span>
                    </Button>
                    <Button
                      size="small"
                      color="default"
                      fill="none"
                      className="action-button"
                    >
                      <MessageOutline />
                      <span style={{ marginLeft: '4px' }}>{post.comment.length}</span>
                    </Button>
                  </Space>
                </div>

                <div style={{ margin: '8px 0' }}>
                  <EnvironmentOutline />
                  <span style={{ marginLeft: 4 }}>{post.address || '暂无地址'}</span>
                </div>

                <List header="评论">
                  {(post.comment || []).map((comment, idx) => (
                    <List.Item 
                      key={`${post._id}-comment-${idx}`}
                      description={formatDateTime(comment.timestamp)}
                    >
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Avatar src={comment.user_id?.img} style={{ marginRight: 8 }} />
                        <div>
                          <div style={{ fontWeight: 'bold' }}>{comment.user_id?.userName || '匿名用户'}</div>
                          <div>{comment.text}</div>
                        </div>
                      </div>
                    </List.Item>
                  ))}
                  <List.Item key={`${post._id}-comment-input`}>
                    <Input 
                      placeholder="添加评论..." 
                      value={commentInputs[post._id] || ''}
                      onChange={(value) => handleCommentInputChange(post._id, value)}
                      onEnterPress={() => handleComment(post._id)}
                    />
                  </List.Item>
                </List>
              </Card>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default SocialFeedPage;
